/*
 * 
 */
package kds.network.http;

import java.util.ArrayList;

import kds.network.HTTPNetworkConfig;
import kds.network.HTTPRequest;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * The Class HTTPRequestLoaderManager.
 * 
 * @author h0akd93
 */
public class HTTPRequestLoaderManager {

	/** The max connections. */
	private static int MAX_CONNECTIONS = HTTPNetworkConfig.DEFAULT_NETWORK_MAX_CONNECTION;

	/** The request manager. */
	public static HTTPRequestLoaderManager requestManager;

	/** The queue */
	private ArrayList<HTTPRequest> queue = new ArrayList<HTTPRequest>();

	/** The active. */
	private ArrayList<HTTPRequest> active = new ArrayList<HTTPRequest>();

	/**
	 * Instantiates a new uRL request manager.
	 */
	private HTTPRequestLoaderManager() {

	}

	/**
	 * @return
	 */
	public static HTTPRequestLoaderManager getRequestQueue() {
		if (requestManager == null)
			requestManager = new HTTPRequestLoaderManager();
		return requestManager;
	}

	/**
	 * Push.
	 * 
	 * @param runnable
	 *            the runnable
	 */
	public void push(HTTPRequest runnable) {
		queue.add(runnable);
		if (active.size() < MAX_CONNECTIONS)
			startNextRequest();

	}

	/**
	 * Start next request.
	 */
	public synchronized void startNextRequest() {
		if (!queue.isEmpty()) {
			HTTPRequest next = queue.get(0);
			queue.remove(0);
			active.add(next);
			Thread thread = new Thread(next);
			thread.start();
		}
	}

	/**
	 * Did request loader.
	 * 
	 * @param runnable
	 *            the runnable
	 */
	public synchronized void didRequestLoader(HTTPRequest runnable) {
		active.remove(runnable);
		startNextRequest();
	}

	/**
	 * Cancel all.
	 */
	public void cancelAll() {
		active.clear();
		for (HTTPRequest r : active)
			r.cancel();
	}

	/**
	 * CheckPerformanceNetwork helper change max conections for performance
	 * thread connection to network.
	 * 
	 * @param context
	 *            the context
	 */
	public void performanceNetwork(Context context) {
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		boolean isWifiConn = networkInfo.isConnected();
		networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean isMobileConn = networkInfo.isConnected();
		if (isMobileConn & !isWifiConn) {
			MAX_CONNECTIONS = HTTPNetworkConfig.PERFORMANCE_SLOW_NETWORK_MAX_CONNECTION;
		} else {
			MAX_CONNECTIONS = HTTPNetworkConfig.PERFORMANCE_FAST_NETWORK_MAX_CONNECTION;
		}
	}

}
